package spring.boot.btc.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

public class HashUtils {

    public static String md5(String text) {
        return DigestUtils.md5Hex(text);
    }

    public static String md5(byte[] text) {
        return DigestUtils.md5Hex(text);
    }

    public static String sha1(String text) {
        return DigestUtils.sha1Hex(text);
    }

    public static String sha1(byte[] text) {
        return DigestUtils.sha1Hex(text);
    }

    public static String sha256(String text) {
        return DigestUtils.sha256Hex(text);
    }

    public static String sha256(byte[] text) {
        return DigestUtils.sha256Hex(text);
    }

    public static String sha512(String text) {
        return DigestUtils.sha512Hex(text);
    }

    public static String sha512(byte[] text) {
        return DigestUtils.sha512Hex(text);
    }

    public static String ripeMD160(String text) throws NoSuchAlgorithmException {
        Security.addProvider(new BouncyCastleProvider());
        MessageDigest ripeMD160 = MessageDigest.getInstance("RipeMD160");
        ripeMD160.update(text.getBytes());
        byte[] ripeMD160Output = ripeMD160.digest();
        return String.format("%032x", new BigInteger(ripeMD160Output));
    }

    public static String ripeMD160(byte[] text) throws NoSuchAlgorithmException {
        Security.addProvider(new BouncyCastleProvider());
        MessageDigest ripeMD160 = MessageDigest.getInstance("RipeMD160");
        ripeMD160.update(text);
        byte[] ripeMD160Output = ripeMD160.digest();
        return String.format("%032x", new BigInteger(ripeMD160Output));
    }


    public static String hash256(String text) {
        return sha256(sha256(text));
    }

    public static String hash256(byte[] text) {
        return sha256(sha256(text));
    }

    public static String hash160(String text) throws NoSuchAlgorithmException {
        return ripeMD160(sha256(text));
    }

    public static String hash160(byte[] text) throws NoSuchAlgorithmException {
        return ripeMD160(sha256(text));
    }
}
